<?php

use app\common\model\Acct;
use app\common\model\Acctjdy;
use app\common\model\Area;
use app\common\model\Custom;
use app\common\model\shop\Goods;
use app\common\model\shop\Ordergoods;
use app\common\model\shop\Unit;
use app\common\model\User;
use com_kingdee_service\Configuration;
use fast\Random;
use GuzzleHttp\Client;
use think\Env;
use think\Log;
use GuzzleHttp\Exception\ClientException;
use think\Cache;
use think\Db;
use app\common\model\Distribution;

class Jdy
{

    protected $openToken;
    protected $appKey = "";
    protected $appSecret = "";
    protected $bookid = "";
    protected $url = "https://api.kingdee.com";

    protected $acct_id = 50;
    protected $outer_id = 316733309617049600;
    protected $appid = 290260;
    protected $appsec = '8f87a25c7db06c2ca862729642243771';
    protected $settle_account_id = "";

    protected $config;
    function __construct($options = [])
    {

        if (!empty($options['acct_id'])) {
            $this->acct_id = $options['acct_id'];
            $this->appKey = Env::get("jdy{$this->acct_id}.appkey");
            $this->appSecret = Env::get("jdy{$this->acct_id}.appscret");
            $this->bookid = Env::get("jdy{$this->acct_id}.bookid");
            $this->appid = Env::get("jdy{$this->acct_id}.appid");
            $this->appsec = Env::get("jdy{$this->acct_id}.appsec");
            $this->outer_id = Env::get("jdy{$this->acct_id}.outer_id");
            $this->settle_account_id = Env::get("jdy{$this->acct_id}.settle_account_id");
        } else {
            $this->appKey = Env::get('jdy.appkey');
            $this->appSecret = Env::get('jdy.appscret');
            $this->bookid = Env::get('jdy.bookid');
            $this->outer_id = Env::get('jdy.outer_id');
            $this->appid = Env::get('jdy.appid');
            $this->appsec = Env::get('jdy.appsec');
        }

        $this->getToken();

        // $this->header = [
        //     "X-Api-ClientID" => $this->openToken,
        //     "X-Api-Auth-Version"=>'2.0',
        //     "X-Api-TimeStamp"=>time(),
        //     "X-Api-SignHeaders"=>'X-Api-TimeStamp,X-Api-Nonce',
        //     "X-Api-Nonce"=>Random::uuid(),
        //     "app-token" => $this->appKey,
        //     "X-GW-Router-Addr" => $this->appSecret,
        //     "content-type" => "application/json",
        // ];
    }




    private function getToken($data = [])
    {
        $this->config = new Configuration();
        $this->config->setAppID($this->appid);
        $this->config->setAppSec($this->appsec);


        $outer_instance_id = $this->outer_id; //"316694292213141504"; // string | outerInstanceId
        $appid = $this->appid; // string | appid

        $cache_id = "1243:kingdee_api_token:{$appid}_{$outer_instance_id}";
        if (Cache::get($cache_id)) {
            $this->config->setAppToken(Cache::get($cache_id));
            return;
        }

        $apiInstance = new com_kingdee_service\data\api\AuthorizeApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        // 316733309617049600
        //316694292213141504
        try {
            $result = $apiInstance->asterAuthorize($outer_instance_id);
            // var_dump($result);
            // die;
            $app_key = $result->data[0]->appKey;
            $app_secret = $result->data[0]->appSecret;
            // var_dump($app_secret);
            // var_dump($result->data[0]);
        } catch (Exception $e) {
            exception($e);
            // echo 'Exception when calling AuthorizeApi->asterAuthorize: ', $e->getMessage(), PHP_EOL;
        }


        // 根据授权信息获取访问凭证
        $apiInstance = new com_kingdee_service\data\api\AppTokenApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $app_signature = base64_encode(hash_hmac('sha256', $app_key, $app_secret, false));; // string | app_signature
        $uid = null; // string | uid
        try {
            $result = $apiInstance->asterAppToken($app_key, $app_signature, $uid);
            $app_token = $result->data->{'app-token'};
            // var_dump($app_token);
            // var_dump($result);
        } catch (Exception $e) {
            exception($e);
            // echo 'Exception when calling AppTokenApi->asterAppToken: ', $e->getMessage(), PHP_EOL;
        }
        Cache::set($cache_id, $app_token, 86000);
        $this->config->setAppToken($app_token);
    }


    function addUser($user)
    {
        $apiInstance = new com_kingdee_service\data\api\EmpApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $id = null; // string | a=id（id与number二选一）;b=2147483647;c=1;d=false.
        $number = '#' . $user->id; // string | a=编码（*id与number二选一）;b=30;c=001;d=false.

        try {
            $result = $apiInstance->empEmpDetail($id, strval($number));
            if ($result->data->id) {
                if (empty($user->jdy_id)) {

                    $user->jdy_id = $result->data->id;
                    $user->save();

                    Acctjdy::create([
                        'acct_id' => 50,
                        'jdy_id' => $result->data->id,
                        'jdy_num' => $number,
                        'type' => 'user'
                    ], true);
                    return $result->data->id;
                } else {
                    if (!Acctjdy::where('acct_id', 50)->where('jdy_num', $number)->where('type', 'user')->value('id')) {
                        Acctjdy::create([
                            'acct_id' => 50,
                            'jdy_id' => $result->data->id,
                            'jdy_num' => $number,
                            'type' => 'user',
                        ], true);
                     
                    }
                    return $result->data->id;
                }
            }
        } catch (Exception $e) {
            // echo 'Exception when calling EmpApi->empEmpDetail: ', $e->getMessage(), PHP_EOL;
        }

        // if(isset($result)){
        //     return;
        // }
        // die;
        $body = new \com_kingdee_service\data\entity\EmpSaveReq(); // \com_kingdee_service\data\entity\EmpSaveReq | 
        $jdy_id = Acctjdy::where('acct_id', 50)->where('jdy_num', $number)->where('type', 'user')->value('jdy_id');
        if ($jdy_id) {
            $body->setId($jdy_id);
        }

        // $acct = Acct::get($user->acct_id);
        // if ($acct) {
        //     if (!$acct->jdy_id) {
        //         $a = $this->addDepartment($acct);
        //         if ($a !== false) {
        //             $acct = $a;
        //         }
        //     }
        //     if ($acct->jdy_id) {
        //         $body->setDepartmentId($acct->jdy_id);
        //     }
        // }


        $body->setNumber($number);
        $body->setMobile($user->mobile);
        $body->setName($user->nickname . '#' . $user->id);
        try {
            $result = $apiInstance->empEmpSave($body);
            if (empty($user->jdy_id) || $user->jdy_id != $result->data->ids[0]) {
                $user->jdy_id = $result->data->ids[0];
                $user->jdy_num = $number;
                $user->save();
                Acctjdy::create([
                    'acct_id' =>50,
                    'jdy_id' => $result->data->ids[0],
                    'jdy_num' => $number,
                    'type' => 'user'
                ], true);
            }
            return $result->data->ids[0] ?? '';
            // print_r($result);
        } catch (Exception $e) {
            Log::error('JDY_用户保存错误' . var_export($e, true));

            exception('用户同步异常' . $e->getMessage());
            // echo 'Exception when calling EmpApi->empEmpSave: ', $e->getMessage(), PHP_EOL;
        }
    }

    function getCustom($number)
    {
        $apiInstance = new com_kingdee_service\data\api\CustomerApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $id = null; // string | a=id（id与number二选一）;b=2147483647;c=1;d=false.
        // $number = $user->id; // string | a=编码（*id与number二选一）;b=30;c=001;d=false.

        try {
            $result = $apiInstance->customerCustomerDetail($id, strval($number));
            if ($result->data->id) {

                return $result->data->id;
            }
        } catch (Exception $e) {
            // echo 'Exception when calling EmpApi->empEmpDetail: ', $e->getMessage(), PHP_EOL;
        }
        return false;
    }

    function addDepartment($acct)
    {
        $apiInstance = new com_kingdee_service\data\api\DepartmentApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\DepartmentSaveReq(); // \com_kingdee_service\data\entity\DepartmentSaveReq | 
        $body->setNumber(strval($acct->id));
        $body->setName($acct->admin->nickname);
        $body->setParentOrgId('100000');
        try {
            $result = $apiInstance->departmentDepartmentSave($body);
            $acct->jdy_id = $result->data->ids[0];
            $acct->jdy_num = strval($acct->id);
            $acct->save();
            return $acct;
            // print_r($result);
        } catch (Exception $e) {
            Log::error('JDY_部门保存错误' . var_export($e, true));
            // echo 'Exception when calling DepartmentApi->departmentDepartmentSave: ', $e->getMessage(), PHP_EOL;
        }
    }

    function getDepartmentList()
    {
        $apiInstance = new com_kingdee_service\data\api\DepartmentApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\DepartmentDepartmentListReq(); // \com_kingdee_service\data\entity\DepartmentDepartmentListReq | 

        try {
            $result = $apiInstance->departmentDepartmentList($body);
            print_r($result);
        } catch (Exception $e) {
            echo 'Exception when calling DepartmentApi->departmentDepartmentList: ', $e->getMessage(), PHP_EOL;
        }
    }

    function addCustom($user)
    {
        $apiInstance = new com_kingdee_service\data\api\CustomerApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $id = null; // string | a=id（id与number二选一）;b=2147483647;c=1;d=false.
        $number = '#' . $user->id; // string | a=编码（*id与number二选一）;b=30;c=001;d=false.


        //         $id = "id_example"; // string | a=id;b=2147483647;c=1;d=true.
        // $number = "number_example"; // string | a=编码;b=30;c=001;d=false.
        // $show_period = true; // bool | a=是否查询周期信息，true-查询，false-不查询；默认为：false;b=1;c=false;d=false.
        // $show_un_visit_days = true; // bool | a=是否显示未拜访天数；默认false-不显示;b=1;c=false;d=false.
        // $show_business_time = true; // bool | a=是否查询客户最近交易时间，true-查询，false-不查询；默认为：false;b=1;c=1;d=false.
        // $show_debt = true; // bool | a=是否查询客户欠款，true-查询，false-不查询；默认为：false;b=1;c=false;d=false.

        // try {
        //     $result = $apiInstance->customerCustomerDetail($id, $number, $show_period, $show_un_visit_days, $show_business_time, $show_debt);
        //     print_r($result);
        // } catch (Exception $e) {
        //     echo 'Exception when calling CustomerApi->customerCustomerDetail: ', $e->getMessage(), PHP_EOL;
        // }


        try {
            $result = $apiInstance->customerCustomerDetail($id, strval($number));

            if ($result->data->id) {
                if (empty($user->jdy_id)) {

                    $user->jdy_id = $result->data->id;
                    $user->jdy_num = $number;
                    $user->save();
                    Acctjdy::create([
                        'acct_id' => 50,
                        'jdy_id' => $result->data->id,
                        'jdy_num' => $number,
                        'type' => 'custom',
                    ], true);
                    return $result->data->id;
                } else {
                    if (!Acctjdy::where('acct_id', 50)->where('jdy_num', $number)->where('type', 'custom')->value('id')) {
                        Acctjdy::create([
                            'acct_id' => 50,
                            'jdy_id' => $result->data->id,
                            'jdy_num' => $number,
                            'type' => 'custom',
                        ], true);
                        
                    }
                    return $result->data->id;
                }
            }
        } catch (Exception $e) {
            // echo 'Exception when calling EmpApi->empEmpDetail: ', $e->getMessage(), PHP_EOL;
        }



        // if(isset($result)){
        //     return;
        // }
        // die;
        $body = new \com_kingdee_service\data\entity\CustomerSaveReq(); // \com_kingdee_service\data\entity\EmpSaveReq | 

        $jdy_id = Acctjdy::where('acct_id', 50)->where('jdy_num', $number)->where('type', 'custom')->value('jdy_id');
        if ($jdy_id) {
            $body->setId($jdy_id);
        }
        $ett = new \com_kingdee_service\data\entity\Contactperson();
        $ett->setContactPerson($user['name']);
        $ett->setMobile($user['phone']);
        $body->setContactpersons([$ett]);

        $body->setNumber($number);
        $body->setName($user['name'] . '#' . $user['id']);
        $body->setAddr($user['address']);

        // $body->setSalerId($user->user->jdy_id ?? '');

        try {
            $result = $apiInstance->customerCustomerSave($body);
            if (empty($user->jdy_id) || $user->jdy_id != $result->data->ids[0]) {
                $user->jdy_id = $result->data->ids[0];
                $user->jdy_num = $number;
                $user->save();
                Acctjdy::create([
                    'acct_id' => 50,
                    'jdy_id' => $result->data->ids[0],
                    'jdy_num' => $number,
                    'type' => 'custom',
                ], true);
            }

            return $result->data->ids[0];

            // print_r($result);
        } catch (Exception $e) {
            Log::error('JDY_客户保存错误' . $e->getMessage() . var_export($body->__toString(), true));
            exception('客户同步异常' . $e->getMessage());
            // echo 'Exception when calling EmpApi->empEmpSave: ', $e->getMessage(), PHP_EOL;
        }
    }



    public function addGoods($goods, $acct_id = 50)
    {
        $a = $this->addUnit($goods->unit);

        $apiInstance = new com_kingdee_service\data\api\MaterialApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $id = null; // string | a=id（id与number二选一）;b=2147483647;c=1;d=false.
        $number = '#' . $goods->id; // string | a=编码（*id与number二选一）;b=30;c=001;d=false.
        if (isset($goods->jdy_num) && $goods->jdy_num) {
            $number = $goods->jdy_num;
        }

        try {
            $result = $apiInstance->materialMaterialDetail($id, strval($number));
            // return true;

            if (!empty($result->data->id)) {

                Acctjdy::create([
                    'acct_id' => $acct_id,
                    'jdy_id' => $result->data->id,
                    'jdy_num' => $number,
                    'type' => 'goods',
                ], true);
            }
            return $result->data->id;
        } catch (Exception $e) {
            // var_dump($e);die;
            // echo 'Exception when calling MaterialApi->materialMaterialDetail: ', $e->getMessage(), PHP_EOL;
        }

        // $apiInstance = new com_kingdee_service\data\api\MaterialApi(
        //     // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
        //     // This is optional, `GuzzleHttp\Client` will be used as default.
        //     new GuzzleHttp\Client(),
        //     $this->config
        // );

        $body = new \com_kingdee_service\data\entity\MaterialSaveRequest(); // \com_kingdee_service\data\entity\MaterialSaveRequest | 

        $body->setNumber($number);
        $body->setName($goods->title);
        $body->setModel($goods->intro);

        $body->setCheckType('1');
        $unit_id = Unit::where('name', $goods->unit)->where('acct_id', $acct_id)->find();
        if ($unit_id) {
            $body->setBaseUnitId((string)$unit_id->jdy_id);
        } else {
            exception('计量单位不存在');
        }
        // var_dump($body);
        // $entt = new \com_kingdee_service\data\entity\PriceEntitySave();
        // $entt->setPriceTradePrice($goods->price);
        // $body->setIsSale(true);
        // $body->setPriceEntity($entt);
        // $body->setRemark($goods->intro);
        // $body->
        try {
            $result = $apiInstance->materialMaterialSave($body);
            if (!empty($result->data->ids[0])) {
                if ($acct_id == 50) {
                    $goods->jdy_id = $result->data->ids[0];
                    $goods->jdy_num = $number;

                    $goods->save();
                }

                Acctjdy::create([
                    'acct_id' => $acct_id,
                    'jdy_id' => $result->data->ids[0],
                    'jdy_num' => $number,
                    'type' => 'goods',
                ], true);

                return $result->data->ids[0];
                // print_r($result);
            }
        } catch (Exception $e) {
            var_dump($e);
            Log::error('JDY_商品错误' . $e->getMessage() . var_export($body->__toString(), true));

            // echo 'Exception when calling MaterialApi->materialMaterialSave: ', $e->getMessage(), PHP_EOL;
            exception('商品同步异常' . $e->getMessage());
        }
    }


    function getGoods($number)
    {
        $apiInstance = new com_kingdee_service\data\api\MaterialApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $id = null; // string | a=id（id与number二选一）;b=2147483647;c=1;d=false.
        // $number = $goods->id; // string | a=编码（*id与number二选一）;b=30;c=001;d=false.

        // try {
        //     $result = $apiInstance->materialMaterialDetail($id, strval($number));
        //     // return true;
        //     print_r($result);
        // } catch (Exception $e) {
        //     echo 'Exception when calling MaterialApi->materialMaterialDetail: ', $e->getMessage(), PHP_EOL;
        // }
        try {
            $result = $apiInstance->materialMaterialDetail($id, strval($number));
            if ($result->data->id) {

                return $result->data->id;
            }
        } catch (Exception $e) {
            // echo 'Exception when calling EmpApi->empEmpDetail: ', $e->getMessage(), PHP_EOL;
        }
        return false;
    }

    function goodsList()
    {
        $apiInstance = new com_kingdee_service\data\api\MaterialApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );

        $body = new \com_kingdee_service\data\entity\MaterialMaterialListReq(); // \com_kingdee_service\data\entity\MaterialMaterialListReq | 

        try {
            $result = $apiInstance->materialMaterialList($body);
            print_r($result);
        } catch (Exception $e) {
            echo 'Exception when calling MaterialApi->materialMaterialList: ', $e->getMessage(), PHP_EOL;
        }
    }

    //同步业务员
    function syncSalesman()
    {
        $list = User::where('jdy_id', '')->select();
        foreach ($list as $key => $user) {
            $this->addUser($user);
            # code...
        }
    }
    //同步客户
    function syncCustomer()
    {
        // $ids = User::where('jdy_id', 'neq', '')->column('id');
        $list = Custom::where('jdy_id', '')
            // ->where('user_id', 'in', $ids)
            ->select();
        foreach ($list as $key => $user) {
            $this->addCustom($user);
            # code...
        }
    }

    //同步商品
    function syncGoods()
    {
        // $ids = User::where('jdy_id', 'neq', '')->column('id');
        $list = Goods::where('jdy_id', '')
            // ->where('user_id', 'in', $ids)
            ->select();
        foreach ($list as $key => $goods) {
            $this->addGoods($goods);
            # code...
        }
    }

    function area()
    {
        $apiInstance = new com_kingdee_service\data\api\SystemApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\SystemDivisionLoadReq(); // \com_kingdee_service\data\entity\SystemDivisionLoadReq | 

        try {
            $result = $apiInstance->systemDivisionLoad($body);
            foreach ($result->data->rows as $key => $s) {
                Db::name('jdy_area')->insert([
                    'id' => $s->id,
                    'name' => $s->name,
                    'level' => $s->level,
                    'parent_id' => $s->parent_id,
                ]);
                foreach ($s->son_nodes as $key => $c) {
                    Db::name('jdy_area')->insert([
                        'id' => $c->id,
                        'name' => $c->name,
                        'level' => $c->level,
                        'parent_id' => $c->parent_id,
                    ]);

                    foreach ($c->son_nodes as $key => $d) {
                        Db::name('jdy_area')->insert([
                            'id' => $d->id,
                            'name' => $d->name,
                            'level' => $d->level,
                            'parent_id' => $d->parent_id,
                        ]);
                    }
                }
                # code...
            }
            // print_r($result);
        } catch (Exception $e) {
            // Log::error('JDY_单位错误' . $e->getMessage() . var_export($body->__toString(), true));

            echo 'Exception when calling SystemApi->systemDivisionLoad: ', $e->getMessage(), PHP_EOL;
        }
    }

    /**
     * 同步单位
     */
    function syncUnit()
    {
        $apiInstance = new com_kingdee_service\data\api\UnitApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );

        $body = new \com_kingdee_service\data\entity\UnitMeasureUnitListReq(); // \com_kingdee_service\data\entity\UnitMeasureUnitListReq | 
        // $body->setPageSize(20);

        $arr = [];
        // $body->setPage(2);

        try {
            $result = $apiInstance->unitMeasureUnitList($body);
            $arr = array_merge($arr, $result->data->rows);
            for ($i = 1; $i < $result->data->total_page; $i++) {
                $body->setPage($i + 1);

                $result = $apiInstance->unitMeasureUnitList($body);
                // print_r($result);
                $arr = array_merge($arr, $result->data->rows);
            }
        } catch (Exception $e) {
            Log::error('JDY_查询错误' . $e->getMessage() . var_export($body->__toString(), true));

            // echo 'Exception when calling UnitApi->unitMeasureUnitList: ', $e->getMessage(), PHP_EOL;
        }

        for ($i = 0; $i < count($arr); $i++) {
            $has = Unit::where('jdy_id', $arr[$i]->id)->where('acct_id', $this->acct_id)->find();
            if ($has) {
                continue;
            } else {
                Unit::create([
                    'name' => $arr[$i]->name,
                    'jdy_id' => $arr[$i]->id,
                    'acct_id' => $this->acct_id,
                ]);
            }
        }

        $names = Goods::group('unit')->field('unit')->select();

        foreach ($names as $key => $v) {
            $has = Unit::where('name', $v['unit'])->where('acct_id', $this->acct_id)->find();
            if ($has && $has->jdy_id) {
                continue;
            } else {

                $body = new \com_kingdee_service\data\entity\MeasureUnitSaveReq(); // \com_kingdee_service\data\entity\MeasureUnitSaveReq | 
                $body->setName($v['unit']);
                $body->setPrecision('2');
                try {
                    $result = $apiInstance->unitMeasureUnitSave($body);
                    Unit::create([
                        'name' => $v['unit'],
                        'jdy_id' => $result->data->ids[0],
                        'acct_id' => $this->acct_id,
                    ]);
                    // print_r($result);
                } catch (Exception $e) {
                    Log::error('JDY_单位保存错误' . $e->getMessage() . var_export($body->__toString(), true));

                    exception('单位同步异常' . $e->getMessage());
                    // echo 'Exception when calling UnitApi->unitMeasureUnitSave: ', $e->getMessage(), PHP_EOL;
                }
                // die;
            }
            # code...
        }
    }

    public function addUnit($name)
    {
        $apiInstance = new com_kingdee_service\data\api\UnitApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );

        $body = new \com_kingdee_service\data\entity\UnitMeasureUnitListReq(); // \com_kingdee_service\data\entity\UnitMeasureUnitListReq | 


        $has = Unit::where('name', $name)->where('acct_id', $this->acct_id)->find();
        if ($has && $has->jdy_id) {
            return;
        } else {

            $body = new \com_kingdee_service\data\entity\MeasureUnitSaveReq(); // \com_kingdee_service\data\entity\MeasureUnitSaveReq | 
            $body->setName($name);
            $body->setPrecision('2');
            try {
                $result = $apiInstance->unitMeasureUnitSave($body);
                Unit::create([
                    'name' => $name,
                    'acct_id' => $this->acct_id,
                    'jdy_id' => $result->data->ids[0]
                ]);
                // print_r($result);
            } catch (Exception $e) {
                Log::error('JDY_单位增加错误' . $e->getMessage() . var_export($body->__toString(), true));

                exception('单位同步异常' . $e->getMessage());
                // echo 'Exception when calling UnitApi->unitMeasureUnitSave: ', $e->getMessage(), PHP_EOL;
            }
            // die;
        }
    }


    public function addOrder($order)
    {


        $apiInstance = new com_kingdee_service\data\api\SalOrderApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\SalOrderSaveReq(); // \com_kingdee_service\data\entity\SalOrderSaveReq | 
        $body->setBillDate(date('Y-m-d'));

        $emp_id = $this->getUserJdyId($order->user);
        $customer_jdy_id = $this->getCustomJdyId($order->custom);

        // $body->setCustomerId($order->custom['jdy_id'] ?? '');
        // $body->setEmpId($order->user['jdy_id'] ?? '');

        $body->setCustomerId($customer_jdy_id);
        $body->setEmpId($emp_id);
        $body->setBillNo($order->order_no);
        $body->setRemark($order->remark);
        $body->setTotalAmount($order->pay_fee);
        $distributionmodel = Distribution::get($order->distribution_id);
        if ($distributionmodel && $distributionmodel['type'] == 0) {

                $body->setCusBearFeeEntry([
                [
                    'income_amount' => $order->send_fee,
                    'income_comment' => '运费',
                    'income_name_id' => '1'
                ]
            ]);
        }

        // 'value' => $order->distribution->title ?? '',
        // 'value' => $order->total_weight ?? '',

        // if ($order->acct_id == 50) {
        $body->setCustomField([

            'custom_field__1__4hyfcu0ufzv0' => $order->distribution->title ?? '', //配送方式
            'custom_field__1__4i0ni3b3x08z' => $order->total_weight ?? '' //重量斤
        ]);
        // }

        // $body->setCostFee($order->send_fee);
        // $body->setCostFeeEntity([
        //     'fee_records'=>[
        //         [
        //             'amount' => $order->send_fee,
        //             'comment' => '运费'
        //         ]
        //     ]

        // ]);

        $att = [];
        $ordergoods = Ordergoods::where('order_id', $order->id)->select();
        foreach ($ordergoods as $goods) {
            $shop_goods = Goods::where('id', $goods->goods_info_json['id'])->find();
            if ($shop_goods && $goods->total > 0) {
                $goods_jdy_id = $this->getGoodsJdyId($shop_goods,50);
                if ($goods_jdy_id) {
                    $ett = new \com_kingdee_service\data\entity\SalOrderSaveReqMaterialEntity();

                    $ett->setIsFree(false);
                    $ett->setMaterialId((string)$goods_jdy_id);
                    $ett->setTaxPrice($goods->pay_price);
                    $ett->setCess('13');
                    $ett->setQty($goods->total);
                    $unit_id = Unit::where('name', $shop_goods['unit'])->where('acct_id',50)->value('jdy_id');
                    if (!$unit_id) {
                        $this->addUnit($shop_goods['unit']);
                    }
                    $unit_id = Unit::where('name', $shop_goods['unit'])->where('acct_id', 50)->value('jdy_id');

                    $ett->setUnitId((string)$unit_id);

                    $ett->setAmount($goods->pay_price * $goods->total);
                    array_push($att, $ett);

                    // array_push($goodsItem, [
                    //     'productCode' => $goods->goods_info_json['product_code'],
                    //     'warehouseCode' => '01',
                    //     'quantity' => $goods->total,
                    //     'unit' => $goods->goods_info_json['unit'] ? $goods->goods_info_json['unit'] : '袋',
                    //     'price' => $goods->price,
                    //     'amount' => $goods->price * $goods->total,
                    // ]);
                }
            }
            // if (empty($goods->goods_info_json['jdy_id'])) {
            //     $goods_jdy_id = Goods::where('id', $goods->goods_info_json['id'])->value('jdy_id');
            // } else {
            //     $goods_jdy_id = $goods->goods_info_json['jdy_id'];
            // }

        }

        //         contact_city_id	string	false	联系信息-市ID
        // contact_country_id	string	false	联系信息-国家ID
        // contact_district_id	string	false	联系信息-区ID
        // contact_linkman	string	false	联系信息-联系人
        // contact_phone	string	false	联系信息-联系方式
        // contact_province_id	string	false	联系信息-省ID
        $address_arr = explode('/', $order->consign_address);
        if (count($address_arr)) {
            if (!empty($address_arr[0])) {
                $province = $this->getArea($address_arr[0] ?? '', 1);
                if ($province) {
                    $body->setContactProvinceId((string)$province['id']);
                    //区域

                    $city = $this->getArea($address_arr[1] ?? '', 2, $province['id'] ?? 0);
                    if ($city) {
                        $body->setContactCityId((string)$city['id']);

                        // $row['city_id'] = $city->id;
                        $area = $this->getArea($address_arr[2] ?? '', 3, $city['id'] ?? 0);
                        if ($area) {
                            $body->setContactDistrictId((string)$area['id']);
                        }
                    }
                }
            }
            if (!empty($address_arr[3])) {
                $body->setContactAddress($address_arr[3]);
            }
        }
        $body->setContactLinkman($order->consign_name);
        $body->setContactPhone($order->consign_mobile);
        $body->setMaterialEntity($att);
        $body->setOperationKey('audit');


        // 'customizedField' => [
        //         [
        //             'name' => '配送方式',
        //             'value' => $order->distribution->title ?? '',
        //         ],
        //         [
        //             'name' => '总重量',
        //             'value' => $order->total_weight ?? '',
        //         ],
        //         [
        //             'name' => '配送费',
        //             'value' => $order->send_fee ?? 0,
        //         ],
        //         [
        //             'name' => '客户名称',
        //             'value' => $order->custom['name'] ?? '',
        //         ],

        //     ]

        try {
            $result = $apiInstance->salOrderSave($body);
            $order->jdy_id = $result->data->ids[0];
            $this->addPreCredit($order);
        } catch (Exception $e) {
            Log::error('JDY_订单错误' . var_export($e, true) . var_export($body->__toString(), true));
            exception('订单同步异常' . $e->getMessage());
        }
    }

    public function addPreCredit($order)
    {
        $apiInstance = new com_kingdee_service\data\api\ArPreCreditApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );

        // $body = new \com_kingdee_service\data\entity\ArPreCreditSaveRequest(); // \com_kingdee_service\data\entity\ArPreCreditSaveRequest | 
        // $body->setBillDate(date('Y-m-d'));
        // $body->setBillNo($order->order_no);
        // $body->setCustomerId($order->custom['jdy_id'] ?? '');
        // $body->setEmpId($order->user['jdy_id'] ?? '');
        // // $Ett= new  SourceBillEntry
        // // $ett = new \com_kingdee_service\data\entity\();
        // $body->setSourceBillEntryList([
        //     [
        //         'src_bill_id' => $order->jdy_id,
        //         'src_bill_type_id' => 'sal_bill_order',
        //     ]
        // ]);

        // // $ett = new \com_kingdee_service\data\entity\Paye();
        // $body->setPayEntryList([
        //     [
        //         'amount' => $order->pay_fee,
        //         'settle_account_id' => '2038708992410126336',
        //     ]
        // ]);

        $emp_id = $this->getUserJdyId($order->user);
        $customer_jdy_id = $this->getCustomJdyId($order->custom);
        $body = [
            'bill_date' => date('Y-m-d'),
            'bill_no' => $order->order_no,
            // 'customer_id' => $order->custom['jdy_id'] ?? '',
            // 'emp_id' => $order->user['jdy_id'] ?? '',
            'customer_id' => $customer_jdy_id,
            'emp_id' => $emp_id,
            'sel_bill_info_entry' => [
                [
                    'cur_settle_amount' => $order->pay_fee,
                    'src_bill_amount' => $order->pay_fee,
                    'src_inter_id' => $order->jdy_id,
                    'src_bill_type_id' => 'sal_bill_order',
                ]
            ],
            'operate_type' => 'audit',
            'pay_entry_list' => [
                [
                    'amount' => $order->pay_fee,
                    'settle_account_id' => $this->settle_account_id,
                ]
            ]
        ];

        $body = json_encode($body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        // var_dump($body->__toString());
        // var_dump($body);

        try {
            $result = $apiInstance->arPreCreditSave($body);
        } catch (Exception $e) {
            Log::error('JDY_预付单错误' . $e->getMessage() . var_export($body, true));
            // echo 'Exception when calling ArPreCreditApi->arPreCreditSave: ', $e->getMessage(), PHP_EOL;
        }
    }

    function accountList()
    {
        $apiInstance = new com_kingdee_service\data\api\SettlementAccountApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\SettlementAccountSettlementAccountListReq(); // \com_kingdee_service\data\entity\SettlementAccountSettlementAccountListReq | 

        try {
            $result = $apiInstance->settlementAccountSettlementAccountList($body);
            print_r($result);
        } catch (Exception $e) {
            echo 'Exception when calling SettlementAccountApi->settlementAccountSettlementAccountList: ', $e->getMessage(), PHP_EOL;
        }
    }

    public function orderList()
    {
        $url = $this->url . "/accounting/openapi/cc/goodsissue/list/{$this->bookid}";

        $data = [
            // "bizDate" => date('Y-m-d'),
            // "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            // "custVendorCode" => '0001',
            // "warehouseCode" => '0001',
            // "goodsItem" => $goodsItem
            "page" => 1,
            "pageSize" => 10,
            // 'bookid'=>$this->bookid,
        ];
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    // "content-type"=>"application/json",
                ],
                'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            var_dump($res);
            die;
            if ($res['success'] == true) {
            } else {
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            var_dump($e->getResponse()->getBody()->getContents());
        }
    }

    function orderDetail($id)
    {
        $url = $this->url . "/accounting/openapi/cc/goodsissue/query/{$id}/{$this->bookid}";

        $data = [
            // "bizDate" => date('Y-m-d'),
            // "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            // "custVendorCode" => '0001',
            // "warehouseCode" => '0001',
            // "goodsItem" => $goodsItem
            "page" => 1,
            "pageSize" => 10,
            // 'bookid'=>$this->bookid,
        ];
        $client = new Client();
        try {
            $resp = $client->get($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    // "content-type"=>"application/json",
                ],
                // 'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            var_dump($res);
            die;
            if ($res['success'] == true) {
            } else {
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            var_dump($e->getResponse()->getBody()->getContents());
        }
    }


    function getUserJdyId($user)
    {
        $has = Acctjdy::where('jdy_num', $user['jdy_num'])->where('acct_id', 50)->where('type', 'user')->find();
        if ($has) {
            return $has->jdy_id;
        }
        return $this->addUser($user);
    }

    function getCustomJdyId($user)
    {
        $has = Acctjdy::where('jdy_num', $user['jdy_num'])->where('acct_id', 50)->where('type', 'custom')->find();
        if ($has) {
            return $has->jdy_id;
        }
        return $this->addCustom($user);
    }

    function getGoodsJdyId($goods, $acct_id = 50)
    {
        $has = Acctjdy::where('jdy_num', $goods['jdy_num'])->where('acct_id', $acct_id)->where('type', 'goods')->find();
        if ($has) {
            return $has->jdy_id;
        }
        return $this->addGoods($goods, $acct_id);
    }



    public function getIncomeType()
    {
        $apiInstance = new com_kingdee_service\data\api\IncomeApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\IncomePacctTypeListReq(); // \com_kingdee_service\data\entity\IncomePacctTypeListReq | 

        try {
            $result = $apiInstance->incomePacctTypeList($body);
            print_r($result);
        } catch (Exception $e) {
            echo 'Exception when calling IncomeApi->incomePacctTypeList: ', $e->getMessage(), PHP_EOL;
        }
    }
    function common($type, $ids, $operate_type)
    {
        $apiInstance = new com_kingdee_service\data\api\SystemApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\CommonOperateRequest(); // \com_kingdee_service\data\entity\CommonOperateRequest | 
        $body->setEntityNumber($type);
        $body->setIds($ids);
        $body->setOperateType($operate_type);
        try {
            $result = $apiInstance->systemCommonOperate($body);
            // print_r($result);
        } catch (Exception $e) {
            Log::error('JDY_操作错误' . $e->getMessage() . var_export($body->__toString(), true));
            exception($e->getMessage());
            // echo 'Exception when calling SystemApi->systemCommonOperate: ', $e->getMessage(), PHP_EOL;
        }
    }

    function customFields()
    {
        $apiInstance = new com_kingdee_service\data\api\SystemApi(
            // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
            // This is optional, `GuzzleHttp\Client` will be used as default.
            new GuzzleHttp\Client(),
            $this->config
        );
        $body = new \com_kingdee_service\data\entity\SystemCustomFieldReq(); // \com_kingdee_service\data\entity\SystemCustomFieldReq | 
        $body->setEntityNumber('sal_bill_order');
        try {
            $result = $apiInstance->systemCustomField($body);
            print_r($result);
        } catch (Exception $e) {
            echo 'Exception when calling SystemApi->systemCustomField: ', $e->getMessage(), PHP_EOL;
        }
    }

    /**
     * 获取区域ID
     * @Author xy
     * @Date 2023-07-27 10:51:06
     * @LastEditors xy
     * @LastEditTime Do not edit
     * @Description 
     * @param {*} $name
     * @param {*} $level
     */
    function getArea($name, $level = 1, $pid = 0)
    {
        if (!$name) {
            return '';
        }
        if ($pid) {
            if ($name == '市中区') {
                $province = Db::name('jdy_area')->where('name', $name)->where('level', $level)->where('parent_id', $pid)->find();
            } else {
                $province = Db::name('jdy_area')->where(function ($q) use ($name) {
                    $q->where('name', 'like', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name) . '%')->whereOr('name', $name);
                })->where('level', $level)->where('parent_id', $pid)->find();
            }
        } else {
            $province = Db::name('jdy_area')->where(function ($q) use ($name) {
                $q->where('name', 'like', str_replace(['省', '市', '自治区', '特别行政区', '区', '县'], '', $name) . '%')->whereOr('name', $name);
            })->where('level', $level)->find();
        }
        return $province;
    }
}
